package com.fbd.internalcommon.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fbd.internalcommon.dto.TokenResult;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

public class JwtUtils {

    private static final String SIGN = "CGtUyt#@$$";
    private static final String JWT_KEY_PHONE = "phone";
    private static final String JWT_KEY_IDENTITY = "identity";
    private static final String JWT_KEY_TOKENTYPE = "tokenType";

    public static String generatorToken(String passengerPhone , String identity , String tokenType){
        HashMap<String, String> map = new HashMap<>();
        map.put(JWT_KEY_PHONE,passengerPhone);
        map.put(JWT_KEY_IDENTITY,identity);
        map.put(JWT_KEY_TOKENTYPE,tokenType);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,1);
        Date date = calendar.getTime();

        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
//        builder.withExpiresAt(date);
        String sign = builder.sign(Algorithm.HMAC256(SIGN));

        return sign;
    }

    public static TokenResult pareToken(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        String phone = verify.getClaim(JWT_KEY_PHONE).asString();
        String identity = verify.getClaim(JWT_KEY_IDENTITY).asString();
        String tokenType = verify.getClaim(JWT_KEY_TOKENTYPE).asString();
        TokenResult tokenResult = new TokenResult();
        tokenResult.setPhone(phone);
        tokenResult.setIdentity(identity);
        tokenResult.setIdentity(tokenType);
        return tokenResult;
    }

    public static void main(String[] args) {
        String token = generatorToken("18272898450" , "1" , "accessToken");
        System.out.println("生成的token为："+ token);
        TokenResult tokenResult = pareToken(token);
        System.out.println("身份"+ tokenResult.getIdentity());
        System.out.println("手机号"+ tokenResult.getPhone());

    }
}
